using Auth.Infrastructure.Repositories;
using Consul;
using Newtonsoft.Json;
using Process.Api;
using Process.Application.Department;
using Process.Application.Services;
using Process.Application.WorkflowDefintion;
using Process.Domain.Entities;
using Process.Domain.Steps;
using Process.Infrastructure.Repositories;
using Produce.Infrastructure.Repositories;
using SqlSugar;
using WorkflowCore;
using WorkflowCore.Persistence.MySQL;
using Yitter.IdGenerator;



var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddSwaggerGen(x => x.IncludeXmlComments(AppContext.BaseDirectory + "Process.Api.XML"));

builder.Services.AddAutoMapper(typeof(SqlsugarMapper));

YitIdHelper.SetIdGenerator(new IdGeneratorOptions());

// 使用Newtonsoft.Json替代System.Text.Json
builder.Services.AddControllers().AddNewtonsoftJson(options =>
{
    options.SerializerSettings.StringEscapeHandling = StringEscapeHandling.Default;
    options.SerializerSettings.Formatting = Formatting.None;
});
// SqlSugar 注册
//builder.Services.AddSingleton<ISqlSugarClient>(sp =>
//    new SqlSugarClient(new ConnectionConfig
//    {
//        ConnectionString = builder.Configuration.GetConnectionString("Oracle"),
//        DbType = DbType.Oracle,
//        IsAutoCloseConnection = true
//    }));
// SqlSugar 注册
builder.Services.AddScoped<ISqlSugarClient>(sp =>
    new SqlSugarClient(new ConnectionConfig
    {
        ConnectionString = builder.Configuration.GetConnectionString("conn"),
        DbType = DbType.MySql,
        IsAutoCloseConnection = true,
        InitKeyType = InitKeyType.Attribute,
        MoreSettings = new ConnMoreSettings
        {
            IsAutoRemoveDataCache = true,
            IsAutoDeleteQueryFilter = true,
           
        }
    })
);
builder.Services.AddWorkflowDSL();
//Mysql持久化配置
builder.Services.AddWorkflow(options =>
{
    options.UseMySQL(builder.Configuration.GetConnectionString("conn"), false, false);
});


builder.Services.AddScoped<AuditStep>();
builder.Services.AddScoped<StartStep>();
builder.Services.AddScoped<EndStep>();


// 仓储与服务注册（泛型）
builder.Services.AddScoped(typeof(IProcessRepository<>),typeof( ProcessRepository<>));
builder.Services.AddScoped(typeof(IProcessAppService<>),typeof(ProcessAppService<>));
builder.Services.AddScoped(typeof(IOperationAppService<>),typeof(OperationAppService<>));
builder.Services.AddScoped(typeof(ITimeReportingAppService<>), typeof(TimeReportingAppService<>));
builder.Services.AddScoped(typeof(ITicketAppService<>), typeof(TicketAppService<>));
builder.Services.AddScoped(typeof(IProduceModelRepository<>), typeof(ProduceModelRepository<>));
builder.Services.AddScoped(typeof(IAuthRepository<>), typeof(AuthRepository<>));
///注册服务（泛型）
builder.Services.AddScoped<IWrokflowDefintion, WorkflowDefinition>();
builder.Services.AddScoped<IDepartmentService, DepartmentService>();

builder.Services.AddSingleton<IConsulClient, ConsulClient>(p => new ConsulClient(cfg =>
{
    cfg.Address = new Uri("http://120.26.197.100:8500");
    //cfg.Address = new Uri("http://localhost:8500");
}));

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.Userworkflow();

app.UseHttpsRedirection();

app.MapControllers();

StaticConfig.CodeFirst_MySqlTableEngine = "InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_general_ci";


using var scope = app.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<ISqlSugarClient>();
db.CodeFirst.InitTables(typeof(ProcessModel), typeof(OperationModel), typeof(TimeReportingModel),typeof(TicketModel), typeof(DepartmentModel),typeof(WorkflowDefinitionModel),typeof(ProcessAuditModel));

app.UseCors(x => x.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

app.MapGet("/health", () => Results.Ok("Ok"));
var consulClient = app.Services.GetRequiredService<IConsulClient>();
var registration = new AgentServiceRegistration
{
    ID = $"Process-{Guid.NewGuid()}",
    Name = "Process",
    Address = "120.26.197.100",
    Port = 8085,
    //Address = "localhost",
    //Port = 5179, // 请根据实际端口调整r
    Check = new AgentServiceCheck
    {
        HTTP = $"http://120.26.197.100:8085/health",
        //HTTP = $"http://localhost:5179/health",
        Interval = TimeSpan.FromSeconds(10),
        Timeout = TimeSpan.FromSeconds(5),
        DeregisterCriticalServiceAfter = TimeSpan.FromMinutes(1) // 可选：健康检查失败多久后自动移除
    }
};
consulClient.Agent.ServiceRegister(registration).Wait();

app.Run();

record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
    public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
